package org.finesys.common.log.listener;


import org.finesys.common.core.util.StrUtil;
import org.finesys.common.log.config.LogProperties;
import org.finesys.common.log.event.OperateLogEvent;
import org.finesys.system.api.entity.SysLog;
import org.finesys.system.api.service.LogService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.StringUtils;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 异步记录日志
 */
@Slf4j
@RequiredArgsConstructor
public class OperateLogListener {

    private final LogProperties logProperties;
    private final LogService logService;

    @Async
    @EventListener(OperateLogEvent.class)
    @SneakyThrows
    public void saveLog(OperateLogEvent operateLogEvent) {
        Integer maxLength = logProperties.getMaxLength();
        SysLog sysLog = (SysLog) operateLogEvent.getSource();
        //提交数据
        if (StringUtils.hasLength(sysLog.getParamsData())) {
            sysLog.setParamsData(StrUtil.subPre(sysLog.getParamsData(), maxLength));
        }
        logService.add(sysLog);
    }
}
